import { _toast } from "../utils"
import {env_config} from '../request/env'

const types = {
  navigateTo: 'navigateTo',
  switchTab: 'switchTab',
  reLaunch: 'reLaunch',
  redirectTo: 'redirectTo',
  navigateBack: 'navigateBack'
}

const routeTo = ({currentTarget}) => {
  let { type = 'navigateTo', url = '', appid = '', delta} = currentTarget.dataset
  $route({type, url, appid, delta})
}

const checkUrlByPages = (url) => {
  // 判断页面栈中是否存在当前点击的路径，如果存在直接返回对应页面
  let pages = getCurrentPages()
  let len = pages.length
  let index = 0
  let arr = pages.filter((cur, idx) => {
    if(url.indexOf(cur.route) > -1){
      index = idx
      return cur
    }
  })
  return {
    hasUrl: arr.length != 0,
    delta: len - index
  }
}

/**
 * 1. 判断传入url是否有效
 * 2. 判断是小程序路径还是外部H5
 * 3. 判断是返回还是直接为空字符串
 * */ 
const $route = (opts) => {
  let { type = 'navigateTo', url = '', appid = '', delta} = opts
  // 判断appid是否有效，有效进行小程序之间的跳转
  if(appid){
    wx.navigateToMiniProgram({
      appId: appid,
      path: url,
      envVersion: env_config.test ? 'trial' : 'release',
      success(){console.log('小程序跳转成功！')},
      fail(){console.log('小程序跳转失败！')}
    })
    return
  }
  // 判断url是否有效，有效进行url的处理，否则判断是否进行返回操作
  if(url){
    // 点击跳转路径就是当前页面，不做处理
    // let page = $api.getPageByIndex(-1)
    // if(url.indexOf(page.route) > -1){
    //   return
    // }
    // 点击跳转路径在页面栈中存在，直接返回
    // let result = checkUrlByPages(url)
    // if(result.hasUrl){
    //   wx.navigateBack(result)
    //   return
    // }
    // 点击跳转路径是H5路径，用web-view打开，否则直接跳转该url
    if(url.indexOf('http') > -1){
      wx.setStorageSync('urlAndParams', `${url}`)
      route({ url: '../../pages/pay/index', type })
    } else {
      route(opts)
    }
  } else {
    delta ? wx.navigateBack(opts) : ''
  }
}

const route = (opts) => {
  let { type = 'navigateTo', url = ''} = opts
  type = types[type] ? type : 'navigateTo'
  wx[type].call(wx, { url })
}

module.exports = {
  routeTo,
  $route
}